<template>
    <div :class='$style.container'>
        <template v-for='field in fields' :key='field.name'>
            <div :class='[$style.item, field.type == "rangePicker" ? $style.rangePicker : ""]'>
                <div :class='$style.title'><span :class='$style.zhan'>{{$t("zhan").repeat(maxLength - field.title.length)}}</span>{{field.title}}</div>
                <template v-if='field.type == "text" || field.type == "number" || field.type == undefined'>
                    <a-input v-bind="field.attrs || {}" :class='$style.input' type='text' v-model:value='field.value' :allowClear='field.clearable === undefined ? true : field.clearable' :placeholder='field.placeholder || $j($t("input"), field.title)' />
                </template>
                <template v-else-if='field.type == "select"'>
                    <a-select v-bind="field.attrs || {}" :class='$style.input' filterable v-model:value='field.value' :options='field._options' :field-names="{ label: field.labelField || 'label', value: field.valueField || 'value' }" :allowClear='field.clearable === undefined ? true : field.clearable' :placeholder='field.placeholder || $j($t("select"), field.title)'></a-select>
                </template>
                <template v-else-if='field.type == "fetchSelect"'>
                    <FetchSelect v-bind="field.attrs || {}" :class='$style.input' :fetch="field.fetchApi" :label-field="field.labelField" :value-field="field.valueField" :options-field="field.optionsField" v-model:value='field.value' :allowClear='field.clearable === undefined ? true : field.clearable' :placeholder='field.placeholder || $j($t("select"), field.title)' />
                </template>
                <template v-else-if='field.type == "cascader"'>
                    <a-cascader v-bind="field.attrs || {}" :class='$style.input' :label-field="field.labelField" :value-field="field.valueField" :options-field="field.optionsField" v-model:value='field.value' :allowClear='field.clearable === undefined ? true : field.clearable' :placeholder='field.placeholder || $j($t("select"), field.title)' />
                </template>
                <template v-else-if='field.type == "treeSelect"'>
                    <a-tree-select v-bind="field.attrs || {}" :class='$style.input' :field-names="{ label: field.labelField || 'name', value: field.valueField || 'code' }" :tree-data="field._options" v-model:value='field.value' :allowClear='field.clearable === undefined ? true : field.clearable' :placeholder='field.placeholder || $j($t("select"), field.title)' />
                </template>
                <template v-else-if='field.type == "datePicker"'>
                    <a-date-picker :class='$style.input' filterable v-model:value='field.value' v-bind='field.attrs || {}' :allowClear='field.clearable === undefined ? true : field.clearable' :placeholder='field.placeholder || $j($t("select"), field.title)' />
                </template>
                <template v-else-if='field.type == "rangePicker"'>
                    <a-range-picker :class='$style.input' filterable valueFormat='YYYY-MM-DD' v-model:value='field.value' v-bind='field.attrs || {}' :allowClear='field.clearable === undefined ? true : field.clearable' />
                </template>
            </div>
        </template>
        <div :class='$style.button'>
            <a-button type='primary' :loading='loading' @click='search'>{{$t("search")}}</a-button>
            <template v-if='buttons'>
                <template v-for='button in buttons' :key='button.button'>
                    <template v-if='button.button == "add"'><a-button type='primary' @click='button.func' ghost>{{button.text || $t("add")}}</a-button></template>
                    <template v-else-if='button.button == "import"'>
                        <a-upload :disabled="uploading" :showUploadList="false" v-bind="button.attrs" :beforeUpload="(file, fileList) => beforeUpload(file, fileList, button.func)">
                            <a-button :loading="uploading">
                                <UploadOutlined v-if="!uploading" />
                                {{button.text || $t("import")}}
                            </a-button>
                        </a-upload>
                    </template>
                    <template v-else-if='button.button == "export"'><a-button :loading='exportLoading' @click='exportFn(button.func)' tertiary>{{button.text || $t("export")}}</a-button></template>
                </template>
            </template>
            <slot name='button'></slot>
        </div>
    </div>
</template>

<script lang='ts' setup>
import { ref, toRefs } from "vue"
import { UploadOutlined } from '@ant-design/icons-vue'
import FetchSelect from './FetchSelect.vue'

    const props = defineProps<{
        fields : Array<SearchField>,
        buttons? : Array<SearchButton>,
        loading : boolean
    }>()

    const emit = defineEmits<{
        (e : 'search', params : any) : void
    }>()

    const uploading = ref(false)
    const exportLoading = ref(false)

    let { fields } = toRefs(props)
    let maxLength = 0

    fields.value.forEach(async (field) => {
        if(field.title.length > maxLength) {
            maxLength = field.title.length
        }

        if((field.type == 'select' || field.type == 'treeSelect') && field.options) {
            
            let options
            if(typeof field.options == 'function') {
                options = await field.options()
            }else {
                options = field.options
            }

            

            if(Array.isArray(options)) {
                field._options = options
                // options.forEach(option => {
                //     if(typeof option == 'object') {
                //         field._options.push({
                //             label : option[field.labelField as string],
                //             value : option[field.valueField as string]
                //         })
                //     }else {
                //         field._options.push({
                //             label : option,
                //             value : option
                //         })
                //     }
                // })
                
            }else {
                field._options = []
                for(let k in options) {
                    field._options.push({
                        label : field.options[k],
                        value : k
                    })
                }
            }
        }

    })


    function buildQueryParams() {
        let params:any = {}
        fields.value.forEach(field => {
            if(field.value != undefined && field.value !== '') {
                if(field.transform) {
                    const value = field.transform(field.value)
                    if(value !== '' && value !== undefined) {
                        if(typeof value === 'object') {
                            params = Object.assign(params, value)
                        }else {
                            params[field.name || field.dataIndex] = value
                        }
                    }
                }else {
                    params[field.name || field.dataIndex] = field.value
                }
                
            }
        })

        return params
    }

     function search() {
        emit('search', buildQueryParams())
    }

    async function exportFn(fn:(...params:any[]) => void) {
        exportLoading.value = true
        await fn(buildQueryParams())
        exportLoading.value = false
    }

    async function beforeUpload(file:File, fileList:File[], func:(file:File, fileList:File[]) => Promise<void>) {
        uploading.value = true
        func(file, fileList).then(() => {
            uploading.value = false
        })
        return false
    }
    

</script>


<style lang='scss' module>
    .container{
        background: #FFFFFF;
        border-radius: 4px;
        display: flex;
        padding: 24px 16px;
        flex-wrap: wrap;
        column-gap: 90px;
        row-gap: 24px;
        //padding-top: 0;

        // display: grid;
        // grid-template-columns : repeat(4, 1fr);
        // column-gap : 90px;
        // row-gap: 24px;

    }

    .item{
        flex:0 0 calc((100% - 3 * 90px) / 4);
        display: flex;
        align-items: center;
        white-space : nowrap;
        
        gap: 16px;

        &.rangePicker{
            min-width: 330px;
        }

        .title{
            font-size: $fontSize;
            color: #001529;
            text-align: right;
            .zhan{
                user-select: none;
                color: transparent;
            }
        }

        .input{
            flex: 1;
            min-width: 160px;
            //height: 34px;
        }
    }

    .button{
        flex: 1;
        display: flex;
        align-items: center;
        gap: 16px;
        justify-content: right;

        
    }

    @media screen and (max-width:1600px) {
        .container{
            column-gap: 50px;
        }

        .item{
            flex:0 0 calc((100% - 3 * 50px) / 4);
        }
    }

    @media screen and (max-width:1400px) {
        .container{
            column-gap: 50px;
        }

        .item{
            flex:0 0 calc((100% - 2 * 50px) / 3);
        }
    }
</style>